/**
 * @Author: YCKOKO
 * @Date: 2023-04-05
 * @Time:19:10
 * @Description:
 */
public class Graph1 {
    private char[] vertexs;//存放顶点集合
    private int[][] edges;//存放边集合或权值
    private boolean isDriect;//判断图为有向还是无向
    private int numOfedge;//存放边的数目

    //构造函数
    public Graph1(int n, boolean isDriect) {
        vertexs = new char[n];
        edges = new int[n][n];
        numOfedge = 0;
        this.isDriect = isDriect;
    }

    //添加顶点集合，初始化
    public void initVertex(char[] vertexs) {
        for (int i = 0; i < vertexs.length; i++) {
            this.vertexs[i] = vertexs[i];
        }
    }

    //添加边或权值
    public void addEdge(char v1, char v2, int weight) {
        int index1 = getIndexOfVertex(v1);
        int index2 = getIndexOfVertex(v2);
        if (isDriect) {
            edges[index1][index2] = weight;
        } else {
            edges[index1][index2] = weight;
            edges[index2][index1] = weight;
        }
    }


    //获取顶点元素在其数组的下标
    public int getIndexOfVertex(char vertex) {
        for (int i = 0; i < vertexs.length; i++) {
            if (vertexs[i] == vertex) {
                return i;
            }
        }
        return -1;
    }


    //获取顶点的度
    public int getDevOfEdge(char v) {
        int count = 0;
        int index = getIndexOfVertex(v);
        if (!isDriect) {
            for (int i = 0; i < edges.length; i++) {
                if (edges[index][i] != 0) {
                    count++;
                }
            }
        } else {
            //出度
            for (int i = 0; i < edges.length; i++) {
                if (edges[index][i] != 0) {
                    count++;
                }
            }
            //入度
            for (int j = 0; j < edges.length; j++) {
                if (edges[j][index] != 0) {
                    count++;
                }
            }
        }
        return count;
    }

    //打印图
    public void showgraph() {
        for (int i = 0; i < edges.length; i++) {
            for (int j = 0; j < edges.length; j++) {
                System.out.print(edges[i][j]+" ");
            }
            System.out.println();
        }
    }


    public static void main(String[] args) {
        Graph1 graph = new Graph1(4,true);
        char[] vertexs = {'A','B','C','D'};
        graph.initVertex(vertexs);
        graph.addEdge('A','B',1);
        graph.addEdge('A','C',1);
        graph.addEdge('B','D',1);
        graph.addEdge('B','C',1);

        graph.showgraph();
        System.out.println(graph.getDevOfEdge('A'));
        System.out.println(graph.getIndexOfVertex('B'));

    }
}